var recursive = require("recursive-readdir");
var beautify = require('js-beautify');
let path = require("path");
let fs = require("fs");

const modules = [
    "Audio",
    "AudioSource",
    "Action",
    "Animation",
    "Button",
    "Collider",
    "Dynamic Atlas",
    "DragonBones",
    "EditBox",
    "Graphics",
    "Geom Utils",
    "Intersection",
    "Layout",
    "Label Effect",
    "Mask",
    "Mesh",
    "MotionStreak",
    "NodePool",
    "Native Socket",
    "Physics",
    "PageView",
    "PageViewIndicator",
    "ProgressBar",
    "ParticleSystem",
    "RichText",
    "Renderer Texture",
    "Slider",
    "ScrollBar",
    "ScrollView",
    "Spine Skeleton",
    "StudioComponent",
    "Toggle",
    "TiledMap",
    "VideoPlayer",
    "Widget",
    "WebView",
    "3D",
    "3D Primitive",
    "SubContext",
    "TypeScript Polyfill",
    "3D Physics/cannon.js",
    "3D Physics/Builtin",
    "3D Physics Framework",
    "3D Particle",
    "SafeArea"
];

const ignoreFiles = [
    ".DS_Store",
    "*.meta",
    "*.png",
    "*.jpeg",
    "*.gif",
    "*.mp3",
    "*.json",
    "*.atlas"
];

const assets = "./assets/";
const project = "./settings/project.json";

(async () => {
    console.log("MODULES CHECK START --->");
    let usedModules = [];
    recursive(assets, ignoreFiles, async (_err, files) => {
        for (let i = 0; i < files.length; i++) {
            let file = files[i];
            let url = path.join(process.cwd(), file);
            let extname = path.extname(url);
            if (extname === ".ts" || extname === ".prefab" || extname === ".fire") {
                let jsContent = fs.readFileSync(url, { encoding: "utf-8" });
                for (let j = 0; j < modules.length; j++) {
                    let module = modules[j];
                    let indexContent = jsContent.indexOf(`cc.${module}`);
                    if (indexContent > 0) {
                        let indexArray = modules.findIndex(v => v === module);
                        indexArray != -1 && usedModules.push(module);
                        continue;
                    }
                }
            }
        }

        let excluded_modules = modules.filter(v => {
            return usedModules.indexOf(v) == -1;
        });

        console.log("MODULES excluded_modules --->", excluded_modules);
        let strProject = fs.readFileSync(path.join(process.cwd(), project), { encoding: "utf-8" });
        let jsonProject = JSON.parse(strProject);
        jsonProject['excluded-modules'] = excluded_modules;
        fs.writeFileSync(path.join(process.cwd(), project), beautify(JSON.stringify(jsonProject), null, 2, 100), { encoding: "utf-8" });

    });

})();